<?php
/**
 * @author Andrew Willmott <andrew.willmott@omni-fi.net>
 * @copyright Copyright (c) 2011, Andrew Willmott
 * @license http://www.opensource.org/licenses/mit-license.php MIT Licence
 * @version 1.0
 * 
 * The bitcoind startup script fo Ubuntu is taken from http://bitcointalk.org/?topic=965.0
 * by Pavel A. Karoukin <pavel@yepcorp.com>.  Code is assumed to be in the public domain
 *
 * This page allows you to set up your Bitcoin bank.  You should delete it once your setup is complete
 */

require ('functions.inc.php');

//See if the user has made a post or if this is the 1st time they have accessed the page
if ($_POST['dbusername'] != NULL){
	//The user has made a post so we can process it:
	setupSystem(
		$_POST['dbusername'],
		$_POST['dbpassword'],
		$_POST['dbwrite'],
		$_POST['dbwriteport'],
		$_POST['dbreadport'],
		$_POST['dbread'],
		$_POST['dbname'],
		$_POST['dbwriteusername'],
		$_POST['dbwritepassword'],
		$_POST['dbreadusername'],
		$_POST['dbreadpassword'],
		$_POST['dbupdateusername'],
		$_POST['dbupdatepassword'],
		$_POST['adminusername'],
		$_POST['adminpassword'],
		$_POST['publichostname'],
		$_POST['upstreambank'],
		$_POST['sessionfiles'],
		$_POST['webserverusername'],
		$_POST['recaptchapublic'],
		$_POST['recaptchaprivate']
	);
	
	htmlHeader("Setup");
	echo "</head><body><p>Setup Complete</p></body></html>";
}
else {
	 requestInformation();
}


function requestInformation(){
	htmlHeader("Setup");
	echo "</head>\n<body>\n";
	echo "\t<form action=\"setup.php\" method=\"POST\">\n";
	echo "\t\t<h1>Bitcoin Bank setup</h1>\n";
	echo "\t\t<p>This page allows you to quickly set up your Bitcoin bank.  You will need the username and password 
	of a user with permission to create databases.  The setup program will create two users in the database one for 
	read access and one for write access.</p>\n";
	echo "\t\t<p>Username for DB Server<input type=\"text\" name=\"dbusername\" value=\"postgres\" /><br />\n";
	echo "\t\tPassword for DB Server<input type=\"password\" name=\"dbpassword\" /><br />\n";
	echo "\t\tHostname/IP for DB writes<input type=\"text\" name=\"dbwrite\" value=\"localhost\" />\n";
	echo "Port<input type=\"text\" name=\"dbwriteport\" value=\"5432\" /><br />\n";
	echo "\t\tHostname/IP for DB reads<input type=\"text\" name=\"dbread\" value=\"localhost\" /><br />\n";
	echo "Port<input type=\"text\" name=\"dbreadport\" value=\"5432\" /><br />\n";
	echo "\t\tName of database<input type=\"text\" name=\"dbname\" value=\"omni-bill\" /><br />\n";
	echo "\t\tUsername for write access<input type=\"text\" name=\"dbwriteusername\" value=\"omni-bill-w\" />(Will overwrite existing)<br />\n";
	echo "\t\tPassword for write access<input type=\"text\" name=\"dbwritepassword\" value=\"" . randomString() . "\" />(Auto generated)<br />\n";
	echo "\t\tUsername for read  access<input type=\"text\" name=\"dbreadusername\"  value=\"omni-bill-r\" />(Will overwrite existing)<br />\n";
	echo "\t\tPassword for read  access<input type=\"text\" name=\"dbreadpassword\"  value=\"" . randomString() . "\" />(Auto generated)<br />\n";
	echo "\t\tUsername for update  access<input type=\"text\" name=\"dbupdateusername\"  value=\"omni-bill-u\" />(Will overwrite existing)<br />\n";
	echo "\t\tPassword for update  access<input type=\"text\" name=\"dbupdatepassword\"  value=\"" . randomString() . "\" />(Auto generated)<br />\n";
	echo "\t\tAdmin username for bank<input type=\"text\" name=\"adminusername\"  value=\"administrator\" /><br />\n";
	echo "\t\tAdmin password for bank<input type=\"password\" name=\"adminpassword\" /><br />\n";
	echo "\t\tPublic hostname/IP to access this system on<input type=\"text\" name=\"publichostname\"  value=\"bcba.example.com\" /><br />\n";
	echo "\t\tInitial upstream bank<input type=\"text\" name=\"upstreambank\"  value=\"bcba.omni-bill.com\" /><br />\n";
	echo "\t\tLocation of session files<input type=\"text\" name=\"sessionfiles\"  value=\"/tmp/omni-bill\" /><br />\n";
	echo "\t\tUsername web server runs under<input type=\"text\" name=\"webserverusername\"  value=\"www-data\" /><br />\n";
	echo "\t\treCAPTCHA public key<input type=\"text\" name=\"recaptchapublic\"  />(You can get one from <a href='http://www.google.com/recaptcha'>.  If you leave it blank you bank will not use reCAPTCHA to protect signups)</a><br />\n";
	echo "\t\treCAPTCHA private key<input type=\"text\" name=\"recaptchaprivate\"  /><br />\n";
	echo "\t\t<input type='submit' value='setup' />\n";
	echo "\t</form>\n</body>\n</html>";
}

function setupSystem($dbUsername, $dbPassword, $dbWrite, $dbWritePort, $dbReadPort, $dbRead, $dbName, $dbWriteUsername, $dbWritePassword,
			$dbReadUsername, $dbReadPassword, $dbUpdateUsername, $dbUpdatePassword, $adminUsername, $adminPassword,
			$publicHostname, $upstreamBank, $temporaryDirectory, $webserverUser, $recaptchaPublic, $recaptchaPrivate,
			$bitcoinAPIUser = "omnibill", $bitcoinAPIPassword = "EIBFOHEPBHWVORBD", $bitcoinHost = "localhost",
			$bitcoinPort = "8332", $bitcoinUser = "bitcoind", $bitcoinPassword = "EIBFOHEPBHWVORBD"){
	//Create the passwords file
	$fh = fopen("passwords.inc.php", 'w') or abortInstallation("Not able to create passwords.inc.php for writing configuration to");
	fwrite($fh, "<?php\n//This file contains all the constants for connecting to the configuration database\n");
	fwrite($fh, "\$GLOBALS['dbWrite'] 		= \"$dbWrite\";\n");
	fwrite($fh, "\$GLOBALS['dbWritePort'] 		= \"$dbWritePort\";\n");
	fwrite($fh, "\$GLOBALS['dbRead'] 		= \"$dbRead\";\n");
	fwrite($fh, "\$GLOBALS['dbReadPort'] 		= \"$dbReadPort\";\n");
	fwrite($fh, "\$GLOBALS['dbName'] 		= \"$dbName\";\n");
	fwrite($fh, "\$GLOBALS['dbWriteUsername'] 	= \"$dbWriteUsername\";\n");
	fwrite($fh, "\$GLOBALS['dbWritePassword'] 	= \"$dbWritePassword\";\n");
	fwrite($fh, "\$GLOBALS['dbReadUsername'] 	= \"$dbReadUsername\";\n");
	fwrite($fh, "\$GLOBALS['dbReadPassword'] 	= \"$dbReadPassword\";\n");
	fwrite($fh, "\$GLOBALS['dbUpdateUsername'] 	= \"$dbUpdateUsername\";\n");
	fwrite($fh, "\$GLOBALS['dbUpdatePassword'] 	= \"$dbUpdatePassword\";\n");
	fwrite($fh, "\$GLOBALS['temporaryDirectory'] 	= \"$temporaryDirectory\";\n");
	fwrite($fh, "\$GLOBALS['recaptchaPublic'] 	= \"$recaptchaPublic\";\n");
	fwrite($fh, "\$GLOBALS['recaptchaPrivate'] 	= \"$recaptchaPrivate\";\n");
	fwrite($fh, "\$GLOBALS['bitcoinUser'] 		= \"$bitcoinAPIUser\";\n");
	fwrite($fh, "\$GLOBALS['bitcoinPassword'] 	= \"$bitcoinAPIPassword\";\n");
	fwrite($fh, "\$GLOBALS['bitcoinHost'] 		= \"$bitcoinHost\";\n");
	fwrite($fh, "\$GLOBALS['bitcoinPort'] 		= \"$bitcoinPort\";\n");
	fwrite($fh, "?>");
	fclose($fh);
	
	//Create the setup file to run as root
	$fh = fopen("setup-os.php", 'w') or abortInstallation("Not able to create setup-os.php for setting up the bitcoin deamon");
	fwrite($fh, "<?php\n");
	fwrite($fh, "`useradd -d /home/bitcoind  -m -p $bitcoinPassword bitcoind`;\n");
	fwrite($fh, "`mv bitcoind /usr/local/bin/`;\n");
	fwrite($fh, "`chmod +x /usr/local/bin/bitcoind`;\n");
	
	//Inside the setup file create the bitcoin.conf file
	fwrite($fh, "mkdir('/home/$bitcoinUser/.bitcoin/');\n");
	fwrite($fh, "\$fh = fopen('/home/$bitcoinUser/.bitcoin/bitcoin.conf', 'w');\n");
	fwrite($fh, "fwrite(\$fh, '# bitcoin.conf configuration file. Lines beginning with # are comments.
');\n");
	fwrite($fh, "fwrite(\$fh, '# This file was created automatically by the Omni-Bill setup script
');\n");
	fwrite($fh, "fwrite(\$fh, '# Do not edit it unless you know what you are doing as it may cause your bank to stop working
');\n");
	fwrite($fh, "fwrite(\$fh, '

');\n");
	fwrite($fh, "fwrite(\$fh, '# JSON-RPC options (for controlling a running Bitcoin/bitcoind process)

');\n");
	fwrite($fh, "fwrite(\$fh, '# server=1 tells Bitcoin to accept JSON-RPC commands.\n');\n");
	fwrite($fh, "fwrite(\$fh, 'server=1

');\n");
	fwrite($fh, "fwrite(\$fh, '# You must set rpcuser and rpcpassword to secure the JSON-RPC api
');\n");
	fwrite($fh, "fwrite(\$fh, 'rpcuser=$bitcoinAPIUser
');\n");
	fwrite($fh, "fwrite(\$fh, 'rpcpassword=$bitcoinAPIPassword

');\n");
	fwrite($fh, "fwrite(\$fh, '# How many seconds bitcoin will wait for a complete RPC HTTP request.
');\n");
	fwrite($fh, "fwrite(\$fh, '# after the HTTP connection is established.
');\n");
	fwrite($fh, "fwrite(\$fh, 'rpctimeout=30

');\n");
	fwrite($fh, "fwrite(\$fh, '# By default, only RPC connections from localhost are allowed.  Specify
');\n");
	fwrite($fh, "fwrite(\$fh, '# as many rpcallowip= settings as you like to allow connections from
');\n");
	fwrite($fh, "fwrite(\$fh, '# other hosts (and you may use * as a wildcard character):
');\n");
	fwrite($fh, "fwrite(\$fh, '# rpcallowip=10.1.1.34
');\n");
	fwrite($fh, "fwrite(\$fh, '#rpcallowip=192.168.1.*

');\n");
	fwrite($fh, "fwrite(\$fh, '# Listen for RPC connections on this TCP port:
');\n");
	fwrite($fh, "fwrite(\$fh, 'rpcport=$bitcoinPort

');\n");
	fwrite($fh, "fwrite(\$fh, '# As bitcoin banks reduce the number of transactions made on the network
');\n");
	fwrite($fh, "fwrite(\$fh, '# all transactions that the bank does make should be set to 0.01 to give
');\n");
	fwrite($fh, "fwrite(\$fh, '# miners the incentive to continue mining for us');\n");
	fwrite($fh, "fwrite(\$fh, 'paytxfee=0.01');\n");
	fwrite($fh, "fclose(\$fh);\n");
	
	//Change the permissions to read only by the owner
	fwrite($fh, "`chmod 700 /home/$bitcoinUser/.bitcoin`;\n");
	fwrite($fh, "`chmod 600 /home/$bitcoinUser/.bitcoin/bitcoin.conf`;\n");
	//Change the owner to the bitcoin owner
	fwrite($fh, "`chown $bitcoinUser /home/$bitcoinUser/.bitcoin`;\n");
	fwrite($fh, "`chown $bitcoinUser /home/$bitcoinUser/.bitcoin/bitcoin.conf`;\n");
	
	//Create the startup script
	fwrite($fh, "\$fh = fopen('/etc/init.d/bitcoind', 'w');\n");
	fwrite($fh, "fwrite(\$fh, '#! /bin/sh
');\n");
	fwrite($fh, "fwrite(\$fh, '### BEGIN INIT INFO
');\n");
	fwrite($fh, "fwrite(\$fh, '# Provides:          bitcoind
');\n");
	fwrite($fh, "fwrite(\$fh, '# Required-Start:    \$remote_fs
');\n");
	fwrite($fh, "fwrite(\$fh, '# Required-Stop:     \$remote_fs
');\n");
	fwrite($fh, "fwrite(\$fh, '# Default-Start:     2 3 4 5
');\n");
	fwrite($fh, "fwrite(\$fh, '# Default-Stop:      0 1 6
');\n");
	fwrite($fh, "fwrite(\$fh, '# Short-Description: bitcoind daemon startup script
');\n");
	fwrite($fh, "fwrite(\$fh, '# Description:       bitcoind daemon startup script
');\n");
	fwrite($fh, "fwrite(\$fh, '### END INIT INFO

');\n");
	fwrite($fh, "fwrite(\$fh, '# Author: Pavel A. Karoukin <pavel@yepcorp.com>
');\n");
	fwrite($fh, "fwrite(\$fh, '# Modified for Omni-Bill by Andrew Willmott <andrew.willmott@omni-fi.net>

');\n");
	fwrite($fh, "fwrite(\$fh, '# Do NOT \"set -e\"

');\n");
	fwrite($fh, "fwrite(\$fh, '# PATH should only include /usr/* if it runs after the mountnfs.sh script
');\n");
	fwrite($fh, "fwrite(\$fh, 'PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
');\n");
	fwrite($fh, "fwrite(\$fh, 'DESC=\"BitCoin Daemon\"
');\n");
	fwrite($fh, "fwrite(\$fh, 'NAME=/usr/local/bin/bitcoind
');\n");
	fwrite($fh, "fwrite(\$fh, 'DAEMON=\$NAME
');\n");
	fwrite($fh, "fwrite(\$fh, 'DAEMON_ARGS=\"-daemon\"
');\n");
	fwrite($fh, "fwrite(\$fh, 'PIDFILE=/var/run/\$NAME.pid
');\n");
	fwrite($fh, "fwrite(\$fh, 'SCRIPTNAME=/etc/init.d/\$NAME
');\n");
	fwrite($fh, "fwrite(\$fh, 'CHUID=$bitcoinUser:$bitcoinUser

');\n");
	fwrite($fh, "fwrite(\$fh, '# Exit if the package is not installed
');\n");
	fwrite($fh, "fwrite(\$fh, '[ -x \"\$DAEMON\" ] || exit 0

');\n");
	fwrite($fh, "fwrite(\$fh, '# Read configuration variable file if it is present
');\n");
	fwrite($fh, "fwrite(\$fh, '[ -r /etc/default/\$NAME ] && . /etc/default/\$NAME

');\n");
	fwrite($fh, "fwrite(\$fh, '# Load the VERBOSE setting and other rcS variables
');\n");
	fwrite($fh, "fwrite(\$fh, '. /lib/init/vars.sh

');\n");
	fwrite($fh, "fwrite(\$fh, '# Define LSB log_* functions.
');\n");
	fwrite($fh, "fwrite(\$fh, '# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
');\n");
	fwrite($fh, "fwrite(\$fh, '. /lib/lsb/init-functions

');\n");
	fwrite($fh, "fwrite(\$fh, '#
# Function that starts the daemon/service
#
');\n");
	fwrite($fh, "fwrite(\$fh, 'do_start()
');\n");
	fwrite($fh, "fwrite(\$fh, '{
');\n");
	fwrite($fh, "fwrite(\$fh, '   # Return
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   0 if daemon has been started
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   1 if daemon was already running
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   2 if daemon could not be started
');\n");
	fwrite($fh, "fwrite(\$fh, '   start-stop-daemon --start --quiet --pidfile \$PIDFILE --exec \$DAEMON --test > /dev/null \
');\n");
	fwrite($fh, "fwrite(\$fh, '      || return 1
');\n");
	fwrite($fh, "fwrite(\$fh, '   start-stop-daemon --start --quiet --chuid \$CHUID --pidfile \$PIDFILE --exec \$DAEMON -- \
');\n");
	fwrite($fh, "fwrite(\$fh, '      \$DAEMON_ARGS \
');\n");
	fwrite($fh, "fwrite(\$fh, '      || return 2
');\n");
	fwrite($fh, "fwrite(\$fh, '}

');\n");
	fwrite($fh, "fwrite(\$fh, '#
# Function that stops the daemon/service
#
');\n");
	fwrite($fh, "fwrite(\$fh, 'do_stop()
');\n");
	fwrite($fh, "fwrite(\$fh, '{
');\n");
	fwrite($fh, "fwrite(\$fh, '   # Return
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   0 if daemon has been stopped
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   1 if daemon was already stopped
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   2 if daemon could not be stopped
');\n");
	fwrite($fh, "fwrite(\$fh, '   #   other if a failure occurred
');\n");
	fwrite($fh, "fwrite(\$fh, '   \$DAEMON stop
');\n");
	fwrite($fh, "fwrite(\$fh, '   start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile \$PIDFILE --name \$NAME
');\n");
	fwrite($fh, "fwrite(\$fh, '   RETVAL=\"\$?\"
');\n");
	fwrite($fh, "fwrite(\$fh, '   [ \"\$RETVAL\" = 2 ] && return 2
');\n");
	fwrite($fh, "fwrite(\$fh, '   # Wait for children to finish too if this is a daemon that forks
');\n");
	fwrite($fh, "fwrite(\$fh, '   # and if the daemon is only ever run from this initscript.
');\n");
	fwrite($fh, "fwrite(\$fh, '   # If the above conditions are not satisfied then add some other code
');\n");
	fwrite($fh, "fwrite(\$fh, '   # that waits for the process to drop all resources that could be
');\n");
	fwrite($fh, "fwrite(\$fh, '   # needed by services started subsequently.  A last resort is to
');\n");
	fwrite($fh, "fwrite(\$fh, '   # sleep for some time.
');\n");
	fwrite($fh, "fwrite(\$fh, '   start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec \$DAEMON
');\n");
	fwrite($fh, "fwrite(\$fh, '   [ \"\$?\" = 2 ] && return 2
');\n");
	fwrite($fh, "fwrite(\$fh, '   # Many daemons don\'t delete their pidfiles when they exit.
');\n");
	fwrite($fh, "fwrite(\$fh, '   rm -f \$PIDFILE
');\n");
	fwrite($fh, "fwrite(\$fh, '   return \"\$RETVAL\"
');\n");
	fwrite($fh, "fwrite(\$fh, '}

');\n");
	fwrite($fh, "fwrite(\$fh, '#
# Function that sends a SIGHUP to the daemon/service
#
');\n");
	fwrite($fh, "fwrite(\$fh, 'do_reload() {
');\n");
	fwrite($fh, "fwrite(\$fh, '   # If the daemon can reload its configuration without
');\n");
	fwrite($fh, "fwrite(\$fh, '   # restarting (for example, when it is sent a SIGHUP),
');\n");
	fwrite($fh, "fwrite(\$fh, '   # then implement that here.
');\n");
	fwrite($fh, "fwrite(\$fh, '   start-stop-daemon --stop --signal 1 --quiet --pidfile \$PIDFILE --name \$NAME
');\n");
	fwrite($fh, "fwrite(\$fh, '   return 0
');\n");
	fwrite($fh, "fwrite(\$fh, '}

');\n");
	fwrite($fh, "fwrite(\$fh, 'case \"\$1\" in
');\n");
	fwrite($fh, "fwrite(\$fh, '  start)
');\n");
	fwrite($fh, "fwrite(\$fh, '   [ \"\$VERBOSE\" != no ] && log_daemon_msg \"Starting \$DESC\" \"\$NAME\"
');\n");
	fwrite($fh, "fwrite(\$fh, '   do_start
');\n");
	fwrite($fh, "fwrite(\$fh, '   case \"\$?\" in
');\n");
	fwrite($fh, "fwrite(\$fh, '      0|1) [ \"\$VERBOSE\" != no ] && log_end_msg 0 ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '      2) [ \"\$VERBOSE\" != no ] && log_end_msg 1 ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '   esac
');\n");
	fwrite($fh, "fwrite(\$fh, '   ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '  stop)
');\n");
	fwrite($fh, "fwrite(\$fh, '   [ \"\$VERBOSE\" != no ] && log_daemon_msg \"Stopping \$DESC\" \"$NAME\"
');\n");
	fwrite($fh, "fwrite(\$fh, '   do_stop
');\n");
	fwrite($fh, "fwrite(\$fh, '   case \"\$?\" in
');\n");
	fwrite($fh, "fwrite(\$fh, '      0|1) [ \"\$VERBOSE\" != no ] && log_end_msg 0 ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '      2) [ \"\$VERBOSE\" != no ] && log_end_msg 1 ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '   esac
');\n");
	fwrite($fh, "fwrite(\$fh, '   ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '  #reload|force-reload)
');\n");
	fwrite($fh, "fwrite(\$fh, '   #
');\n");
	fwrite($fh, "fwrite(\$fh, '   # If do_reload() is not implemented then leave this commented out
');\n");
	fwrite($fh, "fwrite(\$fh, '   # and leave \'force-reload\' as an alias for \'restart\'.
');\n");
	fwrite($fh, "fwrite(\$fh, '   #
');\n");
	fwrite($fh, "fwrite(\$fh, '   #log_daemon_msg \"Reloading \$DESC\" \"\$NAME\"
');\n");
	fwrite($fh, "fwrite(\$fh, '   #do_reload
');\n");
	fwrite($fh, "fwrite(\$fh, '   #log_end_msg \$?
');\n");
	fwrite($fh, "fwrite(\$fh, '   #;;
');\n");
	fwrite($fh, "fwrite(\$fh, '  restart|force-reload)
');\n");
	fwrite($fh, "fwrite(\$fh, '   #
');\n");
	fwrite($fh, "fwrite(\$fh, '   # If the \"reload\" option is implemented then remove the
');\n");
	fwrite($fh, "fwrite(\$fh, '   # \'force-reload\' alias
');\n");
	fwrite($fh, "fwrite(\$fh, '   #
');\n");
	fwrite($fh, "fwrite(\$fh, '   log_daemon_msg \"Restarting \$DESC\" \"\$NAME\"
');\n");
	fwrite($fh, "fwrite(\$fh, '   do_stop
');\n");
	fwrite($fh, "fwrite(\$fh, '   case \"\$?\" in
');\n");
	fwrite($fh, "fwrite(\$fh, '     0|1)
');\n");
	fwrite($fh, "fwrite(\$fh, '      do_start
');\n");
	fwrite($fh, "fwrite(\$fh, '      case \"\$?\" in
');\n");
	fwrite($fh, "fwrite(\$fh, '         0) log_end_msg 0 ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '         1) log_end_msg 1 ;; # Old process is still running
');\n");
	fwrite($fh, "fwrite(\$fh, '         *) log_end_msg 1 ;; # Failed to start
');\n");
	fwrite($fh, "fwrite(\$fh, '      esac
');\n");
	fwrite($fh, "fwrite(\$fh, '      ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '     *)
');\n");
	fwrite($fh, "fwrite(\$fh, '        # Failed to stop
');\n");
	fwrite($fh, "fwrite(\$fh, '      log_end_msg 1
');\n");
	fwrite($fh, "fwrite(\$fh, '      ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '   esac
');\n");
	fwrite($fh, "fwrite(\$fh, '   ;;
');\n");
	fwrite($fh, "fwrite(\$fh, '  *)
');\n");
	fwrite($fh, "fwrite(\$fh, '   #echo \"Usage: \$SCRIPTNAME {start|stop|restart|reload|force-reload}\" >&2
');\n");
	fwrite($fh, "fwrite(\$fh, '   echo \"Usage: \$SCRIPTNAME {start|stop|restart|force-reload}\" >&2
');\n");
	fwrite($fh, "fwrite(\$fh, '   exit 3
');\n");
	fwrite($fh, "fwrite(\$fh, '   ;;
');\n");
	fwrite($fh, "fwrite(\$fh, 'esac

');\n");
	fwrite($fh, "fwrite(\$fh, ':
');\n");
	fwrite($fh, "fclose(\$fh);\n");

	
	fwrite($fh, "`chmod +x /etc/init.d/bitcoind`;\n");
	fwrite($fh, "`update-rc.d bitcoind defaults`;\n");
	
	fwrite($fh, "?>");
	fclose($fh);
	
	//Create the database
	//Connect to database as administrator
	$dbPostgresConn = pg_connect("host=$dbWrite port=$dbWritePort dbname=postgres user=$dbUsername password=$dbPassword");
	
	//Drop database if it already exists
	pg_query($dbPostgresConn, "DROP DATABASE IF EXISTS \"$dbName\"") or abortInstallation("Not able to drop existing database");
	
	//Create the users
	$query = "DROP ROLE IF EXISTS \"$dbWriteUsername\";
	CREATE ROLE \"$dbWriteUsername\" LOGIN
	ENCRYPTED PASSWORD '$dbWritePassword'
	NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE;
	DROP ROLE IF EXISTS \"$dbReadUsername\";
	CREATE ROLE \"$dbReadUsername\" LOGIN
	ENCRYPTED PASSWORD '$dbReadPassword'
	NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE;
	DROP ROLE IF EXISTS \"$dbUpdateUsername\";
	CREATE ROLE \"$dbUpdateUsername\" LOGIN
	ENCRYPTED PASSWORD '$dbUpdatePassword'
	NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE;";
	#echo "<p>Adding users with query:<br/>\n$query\n</p>\n";
	pg_query($dbPostgresConn, $query) or abortInstallation("Not able to create users");
	
	//Create the database:
	$query = "CREATE DATABASE \"$dbName\"  
	WITH OWNER = \"$dbUsername\"
	ENCODING = 'UTF8'
	TEMPLATE=template0
	TABLESPACE = pg_default
	LC_COLLATE = 'C'
	LC_CTYPE = 'C'
	CONNECTION LIMIT = -1";
	
	#echo "<p>Adding database with query:<br/>\n$query\n</p>\n";
	pg_query($dbPostgresConn, $query) or abortInstallation("Not able to create database");
	
	//Grant access to the database
	$query = "GRANT ALL ON DATABASE \"$dbName\"   TO \"$dbUsername\";
	GRANT CONNECT ON DATABASE \"$dbName\" TO \"$dbWriteUsername\";
	GRANT CONNECT ON DATABASE \"$dbName\" TO \"$dbReadUsername\";
	GRANT CONNECT ON DATABASE \"$dbName\" TO \"$dbUpdateUsername\";";
	#echo "<p>Granting access with:<br/>\n$query\n</p>\n";
	pg_query($dbPostgresConn, $query) or abortInstallation("Not able to grant access to database");
	
	//Import the SQL dump and change the usernames as aproprite
	$fh = fopen("database.sql", 'r') or abortInstallation("Unable to find database import");
	$sqlDump = fread($fh, filesize("database.sql"));
	fclose($fh);
	//Now we have read in the file we can use regexes to replace the defaults with the values the user specified
	$originalValue[0] = "/db-admin-user/";		$userValue[0] = $dbUsername;
	$originalValue[1] = "/db-write-only-user/";	$userValue[1] = $dbWriteUsername;
	$originalValue[2] = "/db-read-only-user/";	$userValue[2] = $dbReadUsername;
	$originalValue[3] = "/db-update-only-user/";	$userValue[3] = $dbUpdateUsername;
	
	$sqlDump = preg_replace($originalValue, $userValue, $sqlDump);
	$dbOmniBillConn = pg_connect("host=$dbWrite port=$dbWritePort dbname=$dbName user=$dbUsername password=$dbPassword") or abortInstallation("not able to connect to new database");
	#echo "<p>Creating database structure with:<br/>\n$sqlDump\n</p>\n";
	pg_query($dbOmniBillConn, $sqlDump) or abortInstallation("Not able to create database structure");
	
	//Now the database is created we can add the admin account to it
	//Create the salt
	$salt = mt_rand(0, 2147483640);
	//Create the password hash
	$password = hash('sha256', "$adminPassword $salt $adminUsername");
	pg_query($dbOmniBillConn, "INSERT INTO user_accounts(user_account_name, user_account_password, 
					user_account_salt, user_account_is_admin) 
					VALUES ('$adminUsername', '$password', $salt, TRUE);") 
					or abortInstallation("Not able to create admin account");
	
	//Create the new temporary directory
	//Delete the existing directory if it exists
	exec("rm -rf $temporaryDirectory");
	mkdir ($temporaryDirectory) or abortInstallation('Not able to create temporary directory');
	//Change the owner to the web server user
	chown ($temporaryDirectory, $webserverUser) or abortInstallation('Not able to set owner on temporary directory');
	//Change the permissions to 700 (Full access to owner, no access to anyone else but root)
	chmod ($temporaryDirectory, 700) or abortInstallation('Not able to set permissions on temporary directory');
	
	//Delete this setup file to prevent it being run again by a malicious user
	unlink('setup.php');
}

function abortInstallation($reason){
	htmlHeader("Setup");
	echo "</head>\n<body>\n";
	echo "\t<h1>Setup Failed</h1>\n\t<p>Setup has failled with the error:<br />\n$reason\n<br />\n";
	echo "\tSetup will now attempt to clean up</p>\n</body>\n</html>";
	
	//Delete passwords file
	exec("rm passwords.inc.php");
	exit();
}

?>